<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item :to="{path:'/goodslist'}">商品列表</el-breadcrumb-item>
			<el-breadcrumb-item>修改商品</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片 -->
		<el-card class="box-card">
			<el-steps :space="200" :active="parseInt(activeName)" finish-status="success" align-center>
				<el-step title="基本信息"></el-step>
				<el-step title="商品参数"></el-step>
				<el-step title="商品属性"></el-step>
				<el-step title="商品图片"></el-step>
				<el-step title="商品描述"></el-step>
				<el-step title="完成"></el-step>
			</el-steps>
			<el-form
				:model="FormData.product"
				:rules="FormRules"
				ref="FormRef"
				label-width="100px"
				:label-position="'top'"
			>
				<el-tabs
					v-model="activeName"
					:tab-position="'left'"
					style="min-height: 200px;"
					:before-leave="leaveTab"
				>
					<el-tab-pane label="基本信息" name="0">
						<el-form-item label="商品名称" prop="ProductName">
							<el-input v-model.trim="FormData.product.ProductName"></el-input>
						</el-form-item>
						<el-form-item label="商品价格" prop="Price">
							<el-input v-model.number="FormData.product.Price" type="number"></el-input>
						</el-form-item>
						<el-form-item label="商品数量" prop="Number">
							<el-input v-model.number="FormData.product.Number" type="number"></el-input>
						</el-form-item>
						<el-form-item label="商品分类" prop="CateID">
							<el-cascader v-model="Cate" :options="options" :props="props" @change="handleChange"></el-cascader>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品参数" name="1">
						<el-form-item :label="item.paramName" v-for="item in ParamsDy" :key="item.id">
							<el-checkbox-group v-model="item.natList">
								<el-checkbox
									v-model="nature.id"
									:label="nature"
									border
									v-for="nature in item.natureList"
									:key="nature.id"
									size="medium"
								>{{nature.paramsNatureName}}</el-checkbox>
							</el-checkbox-group>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品属性" name="2">
						<el-form-item :label="item.paramName" v-for="item in ParamsState" :key="item.id">
							<el-checkbox-group v-model="item.natList">
								<el-checkbox
									v-model="nature.id"
									:label="nature"
									border
									v-for="nature in item.natureList"
									:key="nature.id"
									size="medium"
								>{{nature.paramsNatureName}}</el-checkbox>
							</el-checkbox-group>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品图片" name="3">
						<el-upload
							ref="upload"
							:action="uploadurl"
							:on-change="uploadChange"
							:on-remove="handleRemove"
							:file-list="fileList"
							:before-upload="beforeUpload"
							:before-remove="beforeremove"
							:on-success="uploadsuccess"
							:on-error="uploaderror"
							list-type="picture"
							:headers="uploadheaders"
							:limit="5"
						>
							<el-button slot="trigger" size="small" type="primary">上传图片</el-button>
							<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
						</el-upload>
					</el-tab-pane>
					<el-tab-pane label="商品描述" name="4">
						<el-form-item label="商品描述" prop="Describe">
							<el-input type="textarea" v-model.trim="FormData.product.Describe"></el-input>
						</el-form-item>
						<el-button type="primary" @click="save">修改</el-button>
					</el-tab-pane>
					<el-tab-pane label="完成" name="5">完成</el-tab-pane>
				</el-tabs>
			</el-form>
		</el-card>
	</div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
	created() {
		this.GetCateTree()
	},
	data() {
		return {
			activeName: '0',
			//表单数据字段
			FormData: {
				//基本信息
				product: {
					Id:0,
					ProductName: '',
					Price: 0,
					Number: 0,
					CateID: '',
					Describe: ''
				},
				//图片信息
				productImages: [],
				//产品参数和属性
				productParamsNatures: []
			},
			FormRules: {
				ProductName: [
					{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}
				],
				Price: [
					{
						required: true,
						message: '请输入商品价格',
						trigger: 'blur'
					}
				],
				Number: [
					{
						required: true,
						message: '请输入商品数量',
						trigger: 'blur'
					}
				],
				Describe: [
					{
						required: true,
						message: '请输入商品描述',
						trigger: 'blur'
					}
				]
			},
			//下拉的属性
			props: {
				expandTrigger: 'hover',
				value: 'id',
				label: 'cateName',
				children: 'vcates'
			},
			//下拉数据
			options: [],
			//下拉选择到的数据
			Cate: [],
			//动态参数
			ParamsDy: [],
			//静态属性
			ParamsState: [],
			fileList: []
		}
	},
	methods: {
		//获取下拉中的数据
		GetCateTree() {
			this.$get('/api/Cate/GetCateTree', {
				few: 3
			}).then(res => {
				if (res.code == 0) {
					this.options = res.data
					this.GetProductlist()
				}
			})
		},
		//获取初始数据
		GetProductlist() {
			const pid = this.$route.query.id
			this.$get('/api/Product/GetProductImageParam', { ID: pid }).then(
				res => {
					if (res.code == 0) {
						
						this.FormData.product.Id=res.data.product.id
						this.FormData.product.ProductName =
							res.data.product.productName
						this.FormData.product.Price = res.data.product.price
						this.FormData.product.Number = res.data.product.number
						this.FormData.product.CateID = res.data.product.cateId
						this.FormData.product.Describe =
							res.data.product.describe
						//商品分类
						this.Cate = res.data.cate
						this.FormData.productParamsNatures =
							res.data.productParamsNatures
						this.GetParamsList(0)
						this.GetParamsList(1)
						//图片
						this.getFilelist(res.data.productImages)
					}
				}
			)
		},
		//下拉修改时触发
		handleChange(val) {
			console.log(val)
			if (val.length != 3) {
				this.Cate = []
			}
			this.FormData.product.CateID = this.Cate[2]
			this.GetParamsList(0)
			this.GetParamsList(1)
		},
		//阻止tab跳转
		leaveTab(activeName, oldactiveName) {
			if (this.IsCateNull == false) {
				this.$message('请选择商品分类')
				return this.IsCateNull
			}
			return this.IsCateNull
		},
		//获取商品参数和商品属性
		GetParamsList(type) {
			this.$get('/api/Params/GetParamsList', {
				CateId: this.FormData.product.CateID,
				Type: type
			})
				.then(res => {
					if (res.code == 0) {
						if (type == 0) {
							res.data.forEach(item => {
								const aa = this.FormData.productParamsNatures.findIndex(
									x => x.paramsId == item.id
								)
								item.natList = []
								if (aa == -1) {
									item.natList = item.natureList
								} else {
									const paramNatures = this.FormData
										.productParamsNatures[aa]
									const natures = paramNatures.paramsNatureIds.split(
										','
									)
									natures.forEach(i => {
										const r = item.natureList.findIndex(
											x => x.id == i
										)
										item.natList.push(item.natureList[r])
									})
								}
							})
							this.ParamsDy = res.data
						} else {
							res.data.forEach(item => {
								const aa = this.FormData.productParamsNatures.findIndex(
									x => x.paramsId == item.id
								)
								item.natList = []
								if (aa == -1) {
									item.natList = item.natureList
								} else {
									const paramNatures = this.FormData
										.productParamsNatures[aa]
									const natures = paramNatures.paramsNatureIds.split(
										','
									)
									natures.forEach(i => {
										const r = item.natureList.findIndex(
											x => x.id == i
										)
										item.natList.push(item.natureList[r])
									})
								}
							})
							this.ParamsState = res.data
						}
					}
				})
				.catch(err => {
					console.log(err)
				})
		},
		//移除文件时的钩子
		handleRemove(file) {},
		//文件上传前的钩子
		beforeUpload(file) {
			// 验证文件大小
			if (file.size / 1024 / 1024 > 10) {
				this.$message({
					message: `上传文件大小不能超过10M!`,
					type: 'warning'
				})
				return false
			}
		},
		//文件状态改变时的钩子
		uploadChange(file) {},
		//上传成功的钩子
		uploadsuccess(response) {
			console.log(response)
			if (response.code == 0) {
				let imageinfo = {
					ImageName: response.data.name,
					ImageRealName: response.data.fillename
				}
				this.FormData.productImages.push(imageinfo)
				this.$message({
					type: 'success',
					message: response.msg
				})
				console.log(this.FormData.productImages)
			} else {
				this.message.error(response.msg)
			}
		},
		//上传失败的钩子
		uploaderror(err) {
			console.log(err)
			this.message.error('上传失败')
		},
		//移除文件前的钩子
		beforeremove(file) {
			console.log(file)
			var filenameparam='';
			if(file.response==null){
				filenameparam=file.realName
			}else{
				filenameparam=file.response.data.fillename
			}
			this.$get('/api/Product/DelProductImage', {
				ID:this.FormData.product.Id,
				readName: filenameparam
			})
				.then(res => {
					if (res.code == 0) {
						this.$message({
							type: 'success',
							message: res.msg
						})
						const i = this.FormData.productImages.findIndex(
							x => x.ImageRealName == file.response.data.fillename
						)
						this.FormData.productImages.splice(i, 1)
					} else {
						this.$message.error(res.msg)
						return false
					}
				})
				.catch(err => {
					console.log(err)
					return false
				})
		},
		//提交
		save() {
			console.log(this.FormData)
			this.$refs.FormRef.validate(valid => {
				if (valid) {
					this.FormData.productParamsNatures = this.checkedNatList
					this.$post('/api/Product/EditProductImageParam', {
						product: this.FormData.product,
						productImages: this.FormData.productImages,
						productParamsNatures: this.checkedNatList
					})
						.then(res => {
							if (res.code == 0) {
								this.$message({
									type: 'success',
									message: res.msg
								})
								this.$router.push('/goodslist')
							} else {
								this.$message.error(res.msg)
							}
						})
						.catch(err => {
							console.log(err)
						})
				}
			})
		},
		//初始化图片
		getFilelist(filedata) {
			console.log(filedata)
			filedata.forEach(item => {
				const model = {
					name:item.imageName,
					url:this.baseurl+'upload/'+item.imageRealName,
					realName:item.imageRealName
				}
				const pimg={
					ImageName:item.imageName,
					ImageRealName:item.imageRealName
				}
				console.log(model)
				this.fileList.push(model)
				this.FormData.productImages.push(pimg)
			})
		}
	},
	computed: {
		//判断产品分类是否为空，空则返回false，否则返回true
		IsCateNull() {
			if (this.Cate.length != 3) {
				return false
			} else {
				return true
			}
		},
		//获取请求地址
		...mapGetters(['baseurl']),
		//获取上传文件路径
		uploadurl() {
			return this.baseurl + 'api/UpLoad/Post'
		},
		//获取token
		...mapGetters(['userToken']),
		//获取请求头
		uploadheaders() {
			return {
				myToken: this.userToken
			}
		},
		//获取选中的商品参数和属性
		checkedNatList() {
			const datalist = []
			this.ParamsDy.forEach(function(item) {
				var natureIds = []
				item.natList.forEach(function(x) {
					natureIds.push(x.id)
				})
				const data = {
					ParamsId: item.id,
					ParamsNatureIds: natureIds.join(',')
				}
				datalist.push(data)
			})
			this.ParamsState.forEach(function(item) {
				var natureIds = []
				item.natList.forEach(function(x) {
					natureIds.push(x.id)
				})
				const data = {
					ParamsId: item.id,
					ParamsNatureIds: natureIds.join(',')
				}
				datalist.push(data)
			})
			return datalist
		}
	},
	watch: {}
}
</script>

<style lang="stylus" scoped>
.el-checkbox {
	margin: 0;
	margin-right: 10px;
}

.el-checkbox.is-bordered+.el-checkbox.is-bordered {
	margin: 0;
	margin-right: 10px;
}
</style>